#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

'''
(a>>2)|1 == a/2 + 1
'''
import random

def generate_random_array(max_size: int, max_value: int) -> list :
    length = random.randint(1, max_size )  #random.randint结果包括右边界
    arr = []
    for i in range(length):
        arr.append(random.randint(1, max_value))
    return arr

def copy_array(arr : list) -> list:
    if len(arr) == 0 : return None
# list2 = list1.copy()
    return arr[:]


def is_equal(arr1: list, arr2 : list) -> bool :

        if ((not arr1 and arr2) or (arr1 and not arr2)) :
            return False

        if (not arr1 and not arr2) :
            return True

        if (len(arr1) != len(arr2)) :
            return False

        for i in range(len(arr1)-1):
            return arr1[i] == arr2[i]


def print_array(arr : list) :
    if not arr: return
    print(arr)

def bubble_sort(arr : list):
    n = len(arr)
    if not arr or n < 2 :
        return
    for i in range(n - 1):   #总共循环n-1
        flag = 0
        for j in range(n - i -1):  #每次循环预留最后一个不做比较
            if arr[j] > arr[j+1]:
                arr[j], arr[j+1] = arr[j+1], arr[j]
                flag = 1
        if flag == 0 : break
    return

def main():
    test_time = 500;
    max_size = 100;
    max_value = 100;
    succeed = True;
    for i in range(test_time):
        arr1 = generate_random_array(max_size, max_value)
        arr2 = copy_array(arr1)
        arr3 = copy_array(arr1)
        bubble_sort(arr2)
        arr3.sort()
        if is_equal(arr2, arr3) is False :
            succeed = False
            break
# 相当于三目运算
    print('Nice!' if succeed else 'Fucking fucked!')
    if succeed is False:
        print("bubble_sort\n")
        print_array(arr2)
        print("py sort\n")
        print_array(arr3)
        print("raw\n")
        print_array(arr1)

if __name__ == "__main__":
     main()

'''
1.直接调用序列的sort方法
class Person(object):
    def __init__(self,age,name):
        self.age = age
        self.name = name

def personSort():
    persons = [Person(age,name) for (age,name) in [(12,"lili"),(18,"lulu"),(16,"kaka"),(12,"xixi")]]
    persons.sort(cmp=None,key=lambda x:x.age,reverse=False)
    for element in persons:
        print(f'{element.age},:,{element.name}')

2. 使用operator模块的attrgetter方法，可以达到同时对几个字段排序的目的。本例中就是先对age字段排序，如果age相等再按name排序。
def operatorSort():
    persons = [Person(age,name) for (age,name) in [(12,"lili"),(18,"lulu"),(16,"kaka"),(12,"xixi")]]
    try:
        import operator
    except ImportError:
        cmpfun = lambda x:x.age
    else:
        cmpfun = operator.attrgetter("age","name")

    persons.sort(key = cmpfun, reverse=False)
    for element in persons:
        print(f'{element.age},:,{element.name}')

'''